{% extends "LololTeamBundle::layout.html.twig" %}
{% block lololteam_title %}Team builder{% endblock %}
 
 {% block javascripts %} 
{{ parent() }}

<!-- 
<script type="text/javascript"
	src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.js"></script>
 -->
<script type="text/javascript">

	var selectedChampion = null;
	var selectedTeamSlot = null;

	var team = {};
	var placeholders = {}	
	
	$(document).ready(function() {
		$("#teamName").keyup(function(event) {
			updateSaveButton();
		})
		
		$('.btn-save').on('click', function() {
			return save();
		});

		$('.btn-reset').on('click', function() {
			return reset();
		});		
		
// 		$('.draggable').draggable({ revert: true });
// 		$('.droppable').droppable({
// 		    drop: function() { alert('dropped'); }
// 		});

		$('.draggable').on('click', function() {
			var currentChampion = $(this);
			$('.draggable').each(function(index) {
				var champion = $(this);
				if(currentChampion.is(champion)) {
					if(champion.hasClass('champion-selected')) {
						selectedChampion = null;
						champion.removeClass('champion-selected');
					} else {
						selectedChampion = $(this).attr('id');
						champion.addClass('champion-selected');
					}
				} else if($(this).hasClass('champion-selected')) {
					$(this).removeClass('champion-selected');
				}
			});
		});

		$('.droppable').on('click', function() {
			// If a champion is already selected ...
			if(selectedChampion != null) {
				var id = $(this).attr('id');

				// ... check if duplicate champion in team
				for (var tmpId in team) {
					if(team[tmpId] == selectedChampion) {
						// Clear the champion slot if it was already part of the team
						initializeSlot(tmpId, null);
					}
				}

				initializeSlot(id, selectedChampion);

				updateSaveButton();
			}
		});

		for(var i = 0; i < {{ teamSize }}; i++) {
			placeholders['team'+i] = createEmptyDiv(i);
		}
		
		{% if teamChampions.team is not null %}
			{% for championTeam in teamChampions.champions %}
				initializeSlot( 'team{{ loop.index0 }}', 'champion-{{ championTeam.champion.id }}');
			{% endfor %}
		{%  else %}
			initializeSlots();
		{% endif %}

		
		
		updateSaveButton();
	});

	function createEmptyDiv(id) {
		return createDiv(id, '<small>{{ 'team.empty'|trans }}</small>', '#', '');
	}
	
	function createDiv(id, name, href, src) {
		if(src != '') {
			src = ' src="'+src+'" ';
			datasrc = '';
		} else {
			datasrc = 'data-src="holder.js/48x48/text:' + (id + 1);
		}

		

		return 	'<img id="img-'+id+'" class=""'+
				'	'+datasrc+'" '+src+' />'+
				'	<a href="'+href+'">'+name+'</a>';
	}
	
	function initializeSlots() {
		for(var i = 0; i < {{ teamSize }}; i++) {
			initializeSlot('team'+i, null);
		}
	}

	/**
	 *	Initialize the slot of the given id with the champion given as parameter (format: champion-<ID>, ex. champion-1)
	 */
	function initializeSlot(id, champion) {
		if(champion == null) {
			$('#'+id).html(placeholders[id]);

			// Generates the correct src for placeholder
			Holder.run();
		} else {
			// Create the div with champions infos
 			var name = $('#'+champion+'> a').html();
 			var href = $('#'+champion+'> a').attr('href');
 			var src = $('#'+champion+'> img').attr('src');
	 		
			var div = createDiv(id, name, href, src);
			
			$('#'+id).html(div);

			// Put the champion id into the team
			team[id] = champion;
		}
	}

	/**
	 * Enable/disable the save button according to criterias.
	 */
	function updateSaveButton() {
		if(checkTeam()) {
			$('.btn-save').removeAttr('disabled');
		} else {
			$('.btn-save').attr('disabled','disabled');				
		}
	}

	/**
	 * Check if the the team name and the champions are properly filled.
	 */
	function checkTeam() {
		if($('#teamName').val() == '') {
			return false;
		}
		
		var championsCount = 0;
		for(id in team) {
			championsCount++;
		}
		return championsCount == 5;
	}

	/**
	 * Save the team by making an AJAX call
	 */
	function save() {
		$('#loading-indicator').show();
	    $.post('{{ path('lolol_team_teamSave') }}',               
			{	team0:team['team0'],
             	team1:team['team1'],
             	team2:team['team2'],
             	team3:team['team3'],
             	team4:team['team4'],
             	teamName:$('#teamName').val(),
             	idTeam:$('#idTeam').val()
             	}, 
	            function(response){
             		var info = null;
					if(response.code == 100 && response.success){
						var msg = '';
						if($('#idTeam').val() == '') {
							msg = '{{ 'team.built.ok'|trans }}';
						} else {
							msg = '{{ 'team.edit.ok'|trans }}';
						}
						info = 	
							'<div class="alert alert-info col-xs-10 col-xs-offset-1 col-sm-8 col-sm-offset-2 col-md-6 col-md-offset-3 fade in">'+
							'	<button type="button" class="close" data-dismiss="alert" aria-hidden="true"><small>x</small></button>'+
							'	<p><strong>Info:</strong></p><p>'+msg+'</p>'+
							'</div>';
						$('#idTeam').val(response.id);
					} else {
						info = 	
							'<div class="alert alert-danger col-xs-10 col-xs-offset-1 col-sm-8 col-sm-offset-2 col-md-6 col-md-offset-3 fade in">'+
							'	<button type="button" class="close" data-dismiss="alert" aria-hidden="true"><small>x</small></button>'+
							'	<p><strong>{{ 'alert.error'|trans }}</strong></p><p> '+response.error+'</p>'+
							'</div>';
					}

					$('#team-builder-alert').hide();
					$('#team-builder-alert').html(info);
					$('#team-builder-alert').show('fast');

	    }, "json")
	    .fail(function() {
			info = 	
				'<div class="alert alert-danger col-xs-10 col-xs-offset-1 col-sm-8 col-sm-offset-2 col-md-6 col-md-offset-3 fade in">'+
				'	<button type="button" class="close" data-dismiss="alert" aria-hidden="true"><small>x</small></button>'+
				'	<p><strong>Internal error</strong></p><p> Zgguiiii ... Bipp !!! Tutut! Bippp.... Crrrkrkrkrr!</p>'+
				'</div>';

			$('#team-builder-alert').hide();
			$('#team-builder-alert').html(info);
			$('#team-builder-alert').show('fast');
		 })
	    .always(function() {
	    	$('#loading-indicator').hide();
		});
	      
		return false;
	}

	/**
	 * Reset the team being created
	 */
	function reset() {
		if(confirm('{{ 'team.reset.confirm'|trans }}')) {
			// Reset team
		}
		return false;
	}
	</script>
{% endblock %}

{% block lolol_help_body %}
<ul>
	<li>{{ 'builder.help.attackersOrDefenders'|trans }}</li>
</ul>
{% endblock %}

{% block lolol_alert %}
<div id="team-builder-alert" class="row"></div>
{% endblock %}
{% block lolol_title %}{{ 'team.builder'|trans }}{% endblock %}
{% block lolol_main %}
<div class="row team-builder compacted-gallery">
	<form method="POST" action="">
		<input id="idTeam" type="hidden" value="{% if teamChampions.team is not null %}{{ teamChampions.team.id }}{% endif %}" />
		<div class="row">
			<div class="col-xs-12 col-xs-offset-1">
				<button class="btn btn-primary btn-save" type="submit" disabled>
					<i class="fa fa-save"></i> {{ 'team.save'|trans }}
				</button>
				<button class="btn btn-danger btn-reset" type="submit">
					<i class="fa fa-eraser"></i> {{ 'team.reset'|trans }}
				</button>
			</div>
		</div>
		<br />
		<div class="row">
			<div class="col-xs-5">
				<div class="input-group">
					<span class="input-group-addon"><i class="fa fa-users"></i></span>
					<input type="text" class="form-control"
						placeholder="{{ 'team.name'|trans }}" id="teamName"
						name="teamName" value="{% if teamChampions.team is not null %}{{ teamChampions.team.name }}{% endif %}">
				</div>
			</div>
		</div>
		<br />
		<div class="row">
			<div class="col-xs-3 col-md-2">
				<p>
					<strong class="hidden-xs">{{ 'team.selected'|trans }}</strong>
					<strong class="visible-xs"><small>{{ 'team.selected'|trans }}</small></strong>
				</p>
			</div>
			<div class="col-xs-9 col-md-10">
				<p>
					<strong class="hidden-xs">{{ 'team.pool'|trans }}</strong>
					<strong class="visible-xs"><small>{{ 'team.pool'|trans }}</small></strong>
				</p>
			</div>
		</div>
		<div class="row">
			<div class="col-xs-3 col-md-2 team-selected">
				<div class="row">
					{% if teamChampions.team is null %}
					<div class="col-xs-12 text-center">
						<div id="team0" class="thumbnail droppable vgutter-2"></div>
					</div>
					<div class="col-xs-12 text-center">
						<div id="team1" class="thumbnail droppable vgutter-2"></div>
					</div>
					<div class="col-xs-12 text-center">
						<div id="team2" class="thumbnail droppable vgutter-2"></div>
					</div>
					<div class="col-xs-12 text-center">
						<div id="team3" class="thumbnail droppable vgutter-2"></div>
					</div>
					<div class="col-xs-12 text-center">
						<div id="team4" class="thumbnail droppable vgutter-2"></div>
					</div>
					{% else %}
						{% for champion in teamChampions.champions %}
							<div class="col-xs-12 text-center">
								<div id="team{{ loop.index0 }}" class="thumbnail droppable">
								</div>
							</div>
						{% else %}
							BUG: empty team
						{% endfor %}
					{% endif %}
				</div>
			</div>
			<div class="col-xs-9 col-md-10 gutter-1">
				{% for champion in champions %}
				<div class="col-xs-3 col-sm-2 col-md-1 col-lg-1 text-center">
					<div id="champion-{{ champion.id }}" class="thumbnail draggable vgutter-2">
						<img id="img-champion-{{ champion.id }}" class="img-responsive"
							src="{{ asset(folder ~ '/img/' ~ prefixIcons48 ~ champion.imgName ~suffixIcons) }}"
							alt="{{ champion.name }}" /> <a
							href="{{ path('lolol_app_champion', { 'id': champion.id }) }}"><small>{{
								champion.name }}</small></a>
					</div>
				</div>
				{% else %}
				<div class="col-xs-12">{{ 'team.pool.empty'|trans }}</div>
				{% endfor %}
			</div>
		</div>
	</form>
</div>
{% endblock %}
